package com.codes.controller;

import com.codes.config.token.TokenUtil;
import com.codes.core.common.CConstant;
import com.codes.core.common.result.Result;
import com.codes.core.utils.CommonUtil;
import com.codes.core.utils.RegUtil;
import com.codes.core.utils.UserUtil;
import com.codes.core.utils.loginUtil.IPUtil;
import com.codes.model.User;
import com.codes.service.PermissionSV;
import com.codes.service.RoleSV;
import com.codes.service.UserRoleSV;
import com.codes.service.UserSV;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2020/5/26 10:59
 * @Created by peanut
 */
@RestController
@RequestMapping("/user")
@Validated // 参数校验
@Api(tags = "用户模块")
public class UserCtr {

    @Autowired
    private UserSV userSV;
    @Autowired
    private RoleSV roleSV;
    @Autowired
    private PermissionSV permissionSV;
    @Autowired
    private UserRoleSV userRoleSV;

    @ApiOperation("接口入参详情说明")
    @GetMapping("/ip")
    public Result getIp( HttpServletRequest request){

        String ip = IPUtil.getIP(request);
        String ip2 = IPUtil.getIp2(request);
        System.out.println(ip);

        return  Result.success();
    }


    @PostMapping("/add")  // 必须使用  rest 风格的 请求注解  不认swagger 会生成多个 api
    @ApiOperation( "新增用户")
    @ApiOperationSupport(ignoreParameters = {"id"})
    public Result save(@RequestParam Map<String,Object> map){
        try {

            Integer id = MapUtils.getInteger(map,"id");
            int re = 0;

            String addAccount = MapUtils.getString(map,"account");
            if(null == addAccount || CommonUtil.isContainChinese(addAccount)){
                return    Result.failed("账号不能为空或者包含汉字:"+addAccount);
            }

            User u  = new User();
            u.setAccount(addAccount);
            String phone = MapUtils.getString(map,"phone");
            if(null == phone) return Result.failed("请输入手机号");
            if(!RegUtil.orPhoneNumber(phone))  return Result.failed("请输入正确手机号");

            //对密码进行 md5 加密
            String password = MapUtils.getString(map,"password");
            if (StringUtils.isEmpty(password)) {
                password  = "123456";
            }

            Map m = userSV.selectByAccount(u);
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            map.put("password",md5Password);
            if(null != id){ //  修改用户i信息
                Integer searchId = MapUtils.getInteger(m,"id");
                if(searchId != id) return Result.failed("账号已经存在");
                  re = userSV.updateByMap(map);
                if( re > 0){
                    return  Result.success();
                }
                return Result.failed("用户编辑失败",re);
            }


            if(null != m) return Result.failed("账号已存在");
            userSV.insertByMap(map);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return   Result.failed(e.getMessage());
        }
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆")
    @ApiOperationSupport(ignoreParameters = {"id","userName","phone"})
    public Result login(@RequestBody Map<String,Object> param,   HttpServletRequest request, HttpServletResponse response){
        try {
            String account = MapUtils.getString(param,"account");
            if(null == account){
                return  Result.failed("账号有误");
            }
            String loginPass = MapUtils.getString(param,"password");
            if(null == loginPass){
                return  Result.failed("密码有误");
            }
            String loginType = MapUtils.getString(param,"loginType");
            HttpSession session = request.getSession();
            User user = new User();
            user.setAccount(account);
            user.setPassword(loginPass);

            Map<String,Object> map  = userSV.selectByAccount(user);
            if(null != map && !map.isEmpty()){
                if(map.containsKey("password")){
                    String  pass =map.get("password").toString();
                    loginPass =DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
                    if(loginPass.equals(pass)){
                        //
                        //这里已经登陆成功  loginType  pc   保存session else  保存token
                        if(StringUtils.isNotBlank(loginType) && "pc".equals(loginType)){
                            session.setAttribute(CConstant.SESSIONUSER,map);
                        }else {
                            String token =     TokenUtil.generateToken(MapUtils.getString(map,"account"),1001);
                            map.put("token",token);
                            //      map.put("loginUpdate",0);
                            // 第一次 login 保存 token
                            Map m = new HashMap();
                            m.put("id",MapUtils.getInteger(map,"id"));
                            m.put("token",token);
                            userSV.updateByMap(m);
                        }

                        //  当前用户所有的资源
                        Integer roleId = 0;
                        if(map.containsKey("roleId")) roleId = Integer.parseInt(map.get("roleId").toString());
                        List<Map<String,Object>> permissions = permissionSV.selectPerByRoleId(roleId);
                        session.setAttribute(CConstant.SESSIONMENU,permissions);
                        // 登陆成功
                        return Result.success(map);
                    }else {
                        return  Result.failed("密码有误");
                    }
                }
            }else {
                return Result.failed("账号有误");
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
            return Result.failed("登录失败",e.getMessage());
        }
        return Result.failed("登录失败",0);
    }

    @GetMapping("/get_session")
    @ApiOperation(value = "根据token  获取session 用户")
    public Result getSession(HttpServletRequest request){

        Object session = request.getSession().getAttribute(CConstant.SESSIONUSER);
        return Result.success(session);
    }

    @ApiOperation("根据ID获取用户")
    @GetMapping("/get/{id}")
    public Result get(@ApiParam(name="id",value="11",required=true) @PathVariable String id){

        try {
            User re = userSV.selectByPrimaryKey(Integer.valueOf(id));
            return Result.success(re);
        } catch (Exception e) {
            e.printStackTrace();
          return   Result.failed(e.getMessage());
        }

    }
    @ApiOperation("获取用户详情")
    @PostMapping("/get-user-info")
    public Result getUserInfo(@RequestBody Map<String,Object> map){

        Integer userId = MapUtils.getInteger(map,"userId");
        if(null == userId) return Result.failed("用户id为空");
        Map<String,Object> reMap = userSV.getUserInfo(map);
        return Result.success("用户获取成功",reMap);

    }

    @ApiOperation("获取用户列表")
    @GetMapping("/getuserlist")
    public Result getuserlist(@RequestParam( defaultValue="1",required=true) int   page,
                              @RequestParam( defaultValue="10",required=true) Integer limit,
                              @RequestParam Map<String,Object> map) {

        PageHelper.startPage(page,limit);
       // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> users = userSV.getAllUser(map);
        PageInfo<Map<String, Object>> info = new PageInfo< >(users);
        return Result.pages(info.getList(),(int)info.getTotal());

    }

    @PostMapping("/del")
    @ApiOperation("删除用户BYid")
    public Result delete(Integer id){

        User user = userSV.selectByPrimaryKey(id);
        String account  = user.getAccount();
        if(!CConstant.ADMINXPYD.equals(account)){
            userSV.deleteByPrimaryKey(id);

            return  Result.success();
        }
        return  Result.failed("无此权限操作",0);
    }

    @ApiOperation("获取所有用户:参数 userName,phone,account,roleId")
    @GetMapping("/getall")
    public Result getAllUser(  @RequestParam Map<String,Object> map){

        List<Map<String, Object>> users = userSV.getAllUser(map);
        return Result.success(users);
    }


    // logout
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute(CConstant.SESSIONUSER);
        session.removeAttribute("role");
        return Result.success();

    }

    @PostMapping("/change-pwd")
    public Result updatePwd(@RequestParam Map<String,Object> map,HttpServletRequest request){

        String pwd = MapUtils.getString(map,"password");
        Map user = UserUtil.getSessionUser(request);
        Integer userId = MapUtils.getInteger(user,"id");
        Integer re = 0;
        if(StringUtils.isNotBlank(pwd)){
            if(null != userId){
                String   md5Pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
                map.put("id",userId);
                map.put("password",md5Pwd);
                re = userSV.updateByMap(map);
                return Result.success("密码修改成功");
            }
        }

        return Result.failed("密码修改失败");
    }



    // end

}